package cn.wind.xboot.module.app.v1.controller;

import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.core.utils.BlankUtil;
import cn.wind.xboot.core.exception.ValidationException;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * <p>Title: BaseController</p>
 * <p>Description: TODO</p>
 *
 * @author xukk
 * @version 1.0
 * @date 2018/8/13
 */
public abstract class BaseController {
    @Autowired
    protected RestTemplate restTemplate;
    @Autowired
    protected StringRedisTemplate redisTemplate;
    @Autowired
    protected DozerBeanMapper beanMapper;
    @SneakyThrows
    public void hasNoBlank(Map<String,Object> map){
        for(Map.Entry<String, Object> entry: map.entrySet())
        {
            if(BlankUtil.isBlank(entry.getValue())){
                throw new ValidationException(String.format("%s·不为空",entry.getKey()));
            }
        }

    }
    @SneakyThrows
    public void hasNoBlank(Map<String,Object> map,Set<String> varaibleNames){
        String v= contain(map.keySet(),varaibleNames);
        if(StringUtils.isNotBlank(v)){
            throw new ValidationException(String.format("缺少参数·%s",v));
        }
        for(Map.Entry<String, Object> entry: map.entrySet())
        {
            if(varaibleNames.contains(entry.getKey())&&BlankUtil.isBlank(entry.getValue())){
                    throw new ValidationException(String.format("%s·不为空",entry.getKey()));
            }
        }
    }
    public String contain(Set<String> set1, Set<String> set2) {

        if (set1 == null && set2 == null) {
            return "";
        }

        Iterator ite2 = set2.iterator();


        while (ite2.hasNext()) {
            String v=(String)ite2.next();
            if (!set1.contains(v)) {
                return v ;
            }
        }

        return "";
    }
    public ApiResult modifyBoolean(Boolean flag){
        return ApiResult.Custom(flag,"修改成功","修改失败");
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    @SuppressWarnings("rawtypes")
    public  <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = beanMapper.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }
}
